<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="616px"
      :title="model.text"
      wrapClassName="tenant-modal-container"
      @cancel="closeModal()"
    >
      <div class="tenant-modal-body">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <!-- 上级目录 -->
          <a-form-model-item label="上级目录">
            <a-tree-select
              allowClear
              placeholder="请选择上级目录"
              :replaceFields="{
                children: 'childs',
                title: 'menuName',
                key: 'id',
                value: 'id',
              }"
              v-model="form.parentId"
              :tree-data="parentDirectorySource"
            >
            </a-tree-select>
          </a-form-model-item>
          <!-- 参考项目 -->
          <a-form-model-item
            ref="tenantCode"
            label="参考项目"
            prop="tenantCode"
          >
            <a-tree-select
              placeholder="请选择参考项目"
              :replaceFields="{
                children: 'child',
                title: 'tenantName',
                key: 'id',
                value: 'tenantCode',
              }"
              v-model="form.tenantCode"
              :tree-data="consultTenantSource"
              @change="consultTenantChange"
            >
            </a-tree-select>
          </a-form-model-item>
          <!-- 菜单 -->
          <a-form-model-item ref="menuIdList" label="菜单" prop="menuIdList">
            <div
              class="permision-menu-container"
              :class="noChoosePermissFlag && 'error'"
            >
              <a-empty v-if="treeData.length == 0" />
              <a-tree
                v-else
                v-model="checkedKeys"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                @expand="onExpand"
                @check="onCheck"
                :replaceFields="{
                  title: 'menuName',
                  key: 'id',
                  value: 'id',
                  children: 'childs',
                }"
              />
            </div>
          </a-form-model-item>
          <!-- 菜单类型 -->
          <a-form-model-item
            ref="isSystemMenu"
            label="菜单类型"
            prop="isSystemMenu"
          >
            <a-select v-model="form.isSystemMenu" placeholder="请选择菜单类型">
              <a-select-option value="0"> 业务菜单 </a-select-option>
              <a-select-option value="1"> 配置中心</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="form-footer flex">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button type="primary" :loading="loading" @click="submitForm()">
          提交
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  getParentDirectory,
  getConsultTenant,
  getTenantPermissionList,
  getTenantPermissionYYAdd,
} from "@/api/user-center/tenantManage.js";
import { notificationTip, addAttributeByKey, getLinkDataByKey } from "@/utils";
export default {
  name: "referenceTenantModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    model: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getParentDirectoryList();
          this.getConsultTenantList();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      loading: false,
      form: {
        //上级目录
        parentId: undefined,
        //参考目录
        tenantCode: undefined,
        //菜单
        menuIdList: [],
        //菜单类型
        isSystemMenu: undefined,
      },
      rules: {
        tenantCode: [
          { required: true, message: "请选择参考目录", trigger: "change" },
        ],
        menuIdList: [
          { required: true, validator: this.checkAge, trigger: "change" },
        ],
        isSystemMenu: [
          { required: true, message: "请选择菜单类型", trigger: "change" },
        ],
      },
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      noChoosePermissFlag: false,
      //上级目录
      parentDirectorySource: [],
      //参考项目
      consultTenantSource: [],
    };
  },
  mounted() {},
  methods: {
    //查询上级目录
    getParentDirectoryList() {
      let { tenantCode } = this.$route.query;
      getParentDirectory({ tenantCode })
        .then((res) => {
          let { data } = res;
          let tree = data?.result || [];
          this.parentDirectorySource = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            tree,
            "childs"
          );
        })
        .catch((_) => {
          this.parentDirectorySource = [];
        })
        .finally((_) => {});
    },
    //查询参考项目
    getConsultTenantList() {
      getConsultTenant({ tenantName: "" })
        .then((res) => {
          let { data } = res;
          let tree = data?.result || [];
          this.consultTenantSource = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            tree,
            "child"
          );
        })
        .catch((_) => {
          this.consultTenantSource = [];
        })
        .finally((_) => {});
    },
    //选择参考项目
    consultTenantChange() {
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.noChoosePermissFlag = false;
      this.getMenuList();
    },
    //查询菜单
    getMenuList() {
      let { tenantCode } = this.form;
      getTenantPermissionList({
        tenantCode,
        menuName: "",
        menuTypeValue: "",
      })
        .then((res) => {
          let { data } = res;
          let tree = data?.result || [];
          this.treeData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            tree,
            "childs"
          );
        })
        .catch((_) => {
          this.treeData = [];
        })
        .finally((_) => {});
    },

    //递归树状数据
    dealWithTree(treeList, newTreeList) {
      treeList.map((item) => {
        let tempData = {
          id: item.id,
        };
        if (item.childs && item.childs.length > 0) {
          tempData.menuIdList = [];
          this.dealWithTree(item.childs, tempData.menuIdList);
        }
        newTreeList.push(tempData);
      });
    },
    //处理提交的菜单
    setDealWithMenu() {
      this.form.menuIdList = [];
      let twoArray = [];
      let dealArray = [];
      this.checkedKeys.forEach((item) => {
        twoArray.push(
          getLinkDataByKey(item, "id", this.treeData, false, "childs")
        );
      });
      twoArray.forEach((item) => {
        if (item.length != 0) {
          dealArray.push(item);
        }
      });
      let array = dealArray.reduce(function (a, b) {
        return a.concat(b);
      });
      this.dealWithTree(array, this.form.menuIdList);
    },
    //提交
    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.setDealWithMenu();
          let { form } = this;
          let { tenantCode } = this.$route.query;
          let { text } = this.model;
          let formJson = {
            parentId: form.parentId ? form.parentId : "",
            //参考目录
            tenantCode: form.tenantCode,
            //菜单
            menuIdList: form.menuIdList,
            //菜单类型
            isSystemMenu: form.isSystemMenu,
            tenantCode,
          };
          getTenantPermissionYYAdd(formJson)
            .then((res) => {
              notificationTip("success", text + "成功！");
              this.closeModal();
              this.$parent.getTableData();
            })
            .catch((_) => {})
            .finally((_) => {
              this.loading = false;
            });
        }
      });
    },

    //自定义权限菜单校验
    checkAge(rule, value, callback) {
      let { checkedKeys } = this;
      if (checkedKeys.length == 0) {
        this.noChoosePermissFlag = true;
        return callback(new Error("请选择权限菜单"));
      } else {
        this.noChoosePermissFlag = false;
        callback();
      }
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.noChoosePermissFlag = false;
      this.checkedKeys = checkedKeys;
      this.$refs.menuIdList.onFieldChange();
    },
    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //重置表单
    resetForm() {
      this.form = {
        //上级目录
        parentId: undefined,
        //参考目录
        tenantCode: undefined,
        //菜单
        menuIdList: [],
        //菜单类型
        isSystemMenu: undefined,
      };
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.noChoosePermissFlag = false;
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.tenant-modal-container {
  .ant-modal-body {
    padding: 20px 60px;
    .tenant-modal-body {
      .ant-form-item {
        .flex();
        .ant-form-item-label {
          flex-shrink: 0;
          width: 80px;
        }
        .ant-form-item-control-wrapper {
          flex: 1;
        }
        .permision-menu-container {
          width: 414px;
          height: 278px;
          background: #ffffff;
          border: 1px solid #d4d7d8;
          border-radius: 4px;
          .custom-scrollbar();
          &.error {
            border-color: red;
          }
          .ant-tree {
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                width: calc(100% - 60px);
              }
            }
          }
        }
      }
    }
    .form-footer {
      justify-content: center;
    }
  }
}
</style>
